﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace BHExtend.Interface
{
    public class CallExtendDllOrExe
    {

        /// <summary>
        /// 用于BH调用ZLHIS电子健康档案部件使用，使用时需要在zlhis安装文件下的apply文件夹下注册zlEmrInterface.dll文件
        /// 作者：卢彦伯
        /// 日期：2018-10-08
        /// </summary>
        /// <param name="connstr">连接zlhis的链接字符串，一般医院为his或orcl</param>
        /// <param name="username">能打开病案审查的用户，如：zlhis</param>
        /// <param name="password">用户密码</param>
        /// <param name="pid">病人id</param>
        /// <param name="pvid">主页ID</param>
        /// <param name="DisplayModel">是否显示</param>
        public static void CallZLEmrInterfaceDLL(string connstr, string username, string password, int pid, int pvid, string DisplayModel)
        {
            dynamic objemrinter = null, InitInterface = null, objcheckconn = null, ShowArchive = null;
            try
            {
                //创建对象，其中zlEmrInterface.clsEmrInterface是dll类中的接口
                objemrinter = Activator.CreateInstance(Type.GetTypeFromProgID("zlEmrInterface.clsEmrInterface"));
                //调用InitInterface方法
                InitInterface = objemrinter.InitInterface(connstr, username, password);
                objcheckconn = objemrinter.CheckConnect();
                if (objcheckconn)
                {
                    ShowArchive = objemrinter.ShowArchive(pid, pvid, DisplayModel);

                }
            }
            catch (Exception ex)
            {
                //写入日志
                string logpath = DateTime.Now.ToString("yyyy-MM-dd");
                string dir = @"C:\APPSOFT\log\";
                //判断文件夹是否存在，不存在则创建文件夹
                bool db = Directory.Exists(dir);
                if (!db)
                {
                    Directory.CreateDirectory(dir);
                }
                //判断文件是否存在，不存在则创建文件
                logpath = dir + logpath + ".log";
                bool b = File.Exists(logpath);
                if (!b)
                {
                    File.Create(logpath);
                }
                StreamWriter sw = new StreamWriter(logpath, true);
                sw.WriteLine(ex.ToString());
                sw.Dispose();
            }
        }


        /// <summary>
        /// 1）第一次启动zlSoftShowArchiveView.exe的时候较慢，需要耐心等待。
        /// 2）偶尔会出现调用zlSoftShowArchiveView.exe空白页或报错，需要在Windows进程中将其关闭即可。
        /// 3）该插件对HIS版本没有要求。
        /// 4）作者：卢彦伯
        /// 5）日期：2018-10-08
        /// </summary>
        /// <param name="Path">zlSoftShowArchiveView.exe的存放路径，建议存放于BH安装目录下，例如：@"C: \zlsoft\client\otherfiles"</param>
        /// <param name="FileName">zlSoftShowArchiveView.exe</param>
        /// <param name="Connstr">HIS主机字符串，例如："(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.X.X)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)))"</param>
        /// <param name="UserName">HIS用户名</param>
        /// <param name="PassWord">HIS密码</param>
        /// <param name="IsConvertPwd">是否转换密码（0或1）</param>
        /// <param name="PID">his中病人ID</param>
        /// <param name="PVID">his中主页ID</param>
        public static void CallZLSoftShowArchiveView(string Path, string FileName, string Connstr, string UserName, string PassWord, int IsConvertPwd, string PID, string PVID)
        {
            //获取当前文件路径  
            string currentpath = Directory.GetCurrentDirectory();
            string filePath1 = currentpath + @"\otherfiles\ZLSoftShowArchiveView.exe";
            string filePath2 = @"C:\APPSOFT\ZLSoftShowArchiveView.exe";
          
            try
            {
                //先结束ZLSoftShowArchiveView进程
                Process[] pro = Process.GetProcesses();//获取已开启的所有进程
                ////遍历所有查找到的进程
                for (int i = 0; i < pro.Length; i++)
                {
                    //判断此进程是否是要查找的进程
                    if (pro[i].ProcessName.ToString().ToLower() == "zlsoftshowarchiveview")
                    {
                        pro[i].Kill();
                        //延迟500ms,可能进程未杀完，就直接启用，则会报错
                        Thread.Sleep(500);
                    }
                }
                //先判断调用文件是否存在，不存在则返回错误消息
                if (!File.Exists(filePath2))
                {
                    //如果指定路径的不存在，则将clinet/otherfiles下的文件移动到c:/appsoft下
                    if (!File.Exists(filePath1) && !File.Exists(filePath2))
                    {
                        MessageBox.Show("ZLSoftShowArchiveView文件不存在，请联系系统管理员！", "ZLSOFT-电子病案查阅");
                    }
                    File.Copy(filePath1, filePath2, true);
                }

                //比较两个文件版本是否一致，不相同则用clinet/otherfiles的部件进行替换
                if (!isValidFileContent(filePath1, filePath2))
                {
                    File.Copy(filePath1, filePath2, true);
                }
            }
            catch (Exception)
            {
                //throw;
            }   
            //打开应用程序
            ProcessStartInfo psi = new ProcessStartInfo();
            if (File.Exists(filePath2))
            {
                psi.WorkingDirectory = @"c:\APPSOFT";
                psi.FileName = "ZLSoftShowArchiveView.exe";
            }
            else
            {
                psi.WorkingDirectory = Path;
                psi.FileName = FileName;
            }
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.Arguments = Connstr + ":" + UserName + ":" + PassWord + ":" + IsConvertPwd + ":" + PID + ":" + PVID;
            //当执行C盘下的ZLSoftShowArchiveView异常后，执行打开ZLBH下的ZLSoftShowArchiveView文件
            try
            {
                Process.Start(psi);
            }
            catch (Exception)
            {
                psi.WorkingDirectory = Path;
                psi.FileName = FileName;
                psi.WindowStyle = ProcessWindowStyle.Hidden;
                psi.Arguments = Connstr + ":" + UserName + ":" + PassWord + ":" + IsConvertPwd + ":" + PID + ":" + PVID;
                Process.Start(psi);
            }
        }

        /// <summary>
        /// 比较两个文件是否相同
        /// </summary>
        /// <param name="filePath1">文件1路径</param>
        /// <param name="filePath2">文件2路径</param>
        /// <returns>bool</returns>
        public static bool isValidFileContent(string filePath1, string filePath2)
        {
            //创建一个哈希算法对象 
            using (HashAlgorithm hash = HashAlgorithm.Create())
            {
                using (FileStream file1 = new FileStream(filePath1, FileMode.Open), file2 = new FileStream(filePath2, FileMode.Open))
                {
                    byte[] hashByte1 = hash.ComputeHash(file1);//哈希算法根据文本得到哈希码的字节数组 
                    byte[] hashByte2 = hash.ComputeHash(file2);
                    string str1 = BitConverter.ToString(hashByte1);//将字节数组装换为字符串 
                    string str2 = BitConverter.ToString(hashByte2);
                    return (str1 == str2);//比较哈希码 
                }
            }
        }

        /// <summary>
        /// 用于调用成都公司BH办公平台窗体
        /// 作者：周驰
        /// 日期：2018-10-08
        /// </summary>
        /// <param name="FormURL">打开窗体的URL地址</param>
        /// <param name="FormName">打开窗体的名称</param>
        /// <param name="BHUsername">用户名</param>
        /// <param name="BHPassword">用户密码</param>

        public static void CallZLBHForm(string FormURL, string FormName, string BHUsername, string BHPassword)
        {
            string UserName = HttpUtility.UrlEncode(BHUsername, Encoding.UTF8);
            string PassWord = HttpUtility.UrlEncode(BHPassword, Encoding.UTF8);
            string Url = FormURL + "&S_S_人员账号=" + BHUsername;
            Url = HttpUtility.UrlEncode(Url, Encoding.UTF8);
            string ShowMSG = "正在打开窗体「" + FormName + "」...";
            ShowMSG = HttpUtility.UrlEncode(ShowMSG, Encoding.UTF8);
            string fileName = string.Format("callzlbh:\\\\{0}|{1}|{2}|{3}", new object[]
            {
                UserName,
                Url,
                PassWord,
                ShowMSG
            });
            Process.Start(fileName);
        }
        /// <summary>
        /// 用于检查删除进程
        /// 作者：廖成志
        /// 日期：2019-01-18
        /// </summary>
        /// <param name="processName">进程名称</param>
        public void killProcess(string processName)
        {
            Process[] pro = Process.GetProcesses();//获取已开启的所有进程
            //遍历所有查找到的进程
            for (int i = 0; i < pro.Length; i++)
            {
                //判断此进程是否是要查找的进程
                if (pro[i].ProcessName.ToString().ToLower() == processName)
                {
                    pro[i].Kill();//结束进程
                }

            }

        }

        /// <summary> 
        /// 1）通过firefox或者chrome打开url
        /// 2）作者：卢彦伯
        /// 3)日期：2019-08-29
        /// </summary>
        /// <param name="url">需要打开的url地址</param>
        /// <param name="browsers">多个浏览器名称用|分割</param>
        /// <param name="alter_msg">需要打开的url地址</param> 

        public void CallUrl(string url, string browsers, string alter_msg)
        {

            bool success = true;
            if (browsers.Length > 0)
            {
                //如果传入制定的
                ///解析插入的浏览器
                string[] browserg = browsers.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < browserg.Length; i++)
                {
                    if (browserg[i] == "firefox.exe")
                    {
                        try
                        {
                            var result = Process.Start("firefox.exe", url);
                            if (result == null)
                            {
                                success = false;
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch
                        {
                            success = false;
                        }
                    }

                    if (browserg[i] == "chrome.exe")
                    {
                        try
                        {
                            var result = Process.Start("chrome.exe", url);
                            if (result == null)
                            {
                                success = false;
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch
                        {
                            success = false;
                        }
                    }

                    if (browserg[i] == "iexplore.exe")
                    {
                        try
                        {
                            var result = Process.Start("iexplore.exe", url);
                            if (result == null)
                            {
                                success = false;
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch
                        {
                            success = false;
                        }
                    }
                    if (success)
                    {
                        MessageBox.Show(alter_msg, "医院信息平台", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                }

                if (!success)
                {
                    MessageBox.Show(alter_msg, "医院信息平台", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

            }
            else
            {
                try
                {
                    var result = Process.Start("chrome.exe", url);
                    if (result == null)
                    {
                        success = false;
                    }
                }
                catch
                {
                    success = false;
                }

                if (!success)
                {
                    try
                    {
                        if (!success)
                        {
                            success = true;
                            var result = Process.Start("chrome.exe", url);
                            if (result == null)
                            {
                                success = false;
                            }
                        }

                    }
                    catch
                    {
                        success = false;
                    }
                }
                if (!success)
                {
                    MessageBox.Show("请安装火狐或者谷歌浏览器！", "医院信息平台", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        /// <summary>
        /// 1）调用英飞达PACS影像借口
        /// 2）作者：卢彦伯
        /// 3)日期：2019-08-29
        /// </summary>
        /// <param name="url">服务器地址</param>
        /// <param name="username">用户名</param>
        /// <param name="password">用户密码</param>
        /// <param name="apply_id">申请ID为医嘱ID</param>
        public void CallINFINITTPACS(string url, string username, string password, string apply_id)
        {

            string param = "http://10.36.240.5" + "+" + username + "+" + password + "++S+" + apply_id;
            if (!File.Exists(@"C:\INFINITT\VIEWER\G3Launcher.exe"))
            {
                MessageBox.Show("本机未安装[英飞达阅片器]！\r\n或者未将软件安装到指定路径[C:\\INFINITT\\VIEWER\\G3Launcher.exe]！", "[pacsviewer]影像阅片", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Environment.Exit(1);
            }
            Process.Start(@"C:\INFINITT\VIEWER\G3Launcher.exe", param);
        }

    }
}
